﻿using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Threading.Tasks;

using Dapper;
using Dapper.Contrib.Extensions;
using Labthink.PCSoft.UniversalHost4.Model;

namespace Labthink.PCSoft.UniversalHost4.DataAccess
{
    public class LogCacheRepository
    {
        private readonly string _file;

        public LogCacheRepository(string file)
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException($"can not find file {file}");
            }

            _file = file;
        }

        public Task<int> AddLogAsync(OperateLog log)
        {
            using (var conn = new SQLiteConnection($"Data Source={_file};Version=3;"))
            {
                conn.Open();
                return conn.InsertAsync(log);
            }
        }

        public Task<int> RemoveLogsAsync()
        {
            using (var conn = new SQLiteConnection($"Data Source={_file};Version=3;"))
            {
                conn.Open();
                return conn.ExecuteScalarAsync<int>("DELETE FROM OperateLogs");
            }
        }

        public Task<IEnumerable<OperateLog>> GetLogsAsync()
        {
            using (var conn = new SQLiteConnection($"Data Source={_file};Version=3;"))
            {
                conn.Open();
                return conn.QueryAsync<OperateLog>("SELECT * FROM OperateLogs");
            }
        }
    }
}
